﻿namespace System.Collections.Dynamic
{
	using System.Collections.Generic;
	using System.Dynamic;

	/// <summary>
	/// Provides access to a string-object dictionary directly through member access.
	/// </summary>
	public class DynamicDictionary : DynamicObject
	{
		/// <summary>
		/// Initializes a new instance of the DynamicDictionary from an already existing dictionary.
		/// </summary>
		/// <param name="dictionary"></param>
		public DynamicDictionary(IDictionary<string, object> dictionary)
		{
			if (dictionary == null)
				throw new ArgumentNullException("dictionary");

			this.dictionary = dictionary;
		}
		/// <summary>
		/// Initializes a new instance of the DynamicDictionary that is empty.
		/// </summary>
		public DynamicDictionary()
			: this(new Dictionary<string, object>())
		{ }

		IDictionary<string, object> dictionary;

		/// <summary>
		/// Gets the number of elements contained in the dictionary.
		/// </summary>
		public int Count
		{
			get { return dictionary.Count; }
		}


		public override bool TryGetMember(GetMemberBinder binder, out object result)
		{
			return dictionary.TryGetValue(binder.Name, out result);
		}

		public override bool TrySetMember(SetMemberBinder binder, object value)
		{
			dictionary[binder.Name] = value;
			return true;
		}


		public override IEnumerable<string> GetDynamicMemberNames()
		{
			return dictionary.Keys;
		}
	}
}
